package com.yantu.controller.wx;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yantu.bean.Message;
import com.yantu.bean.MessageUser;
import com.yantu.bean.User;
import com.yantu.mapper.MessageMapper;
import com.yantu.mapper.MessageUserMapper;
import com.yantu.mapper.UserMapper;
import com.yantu.util.JWTUtil;
import com.yantu.util.RedisUtils;
import com.yantu.util.Result;
import com.yantu.view.PageView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 综合实训课程设计
 * @since 2022-08-15
 */
@RestController
@RequestMapping("/wx")
@Api("消息接口表")
public class WxMessageController extends WxUserFatherController {

    @Autowired
    MessageMapper messageMapper;

    @Autowired
    MessageUserMapper messageUserMapper;

    @Autowired
    JWTUtil jwtUtil;

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisUtils redisUtils;

    //消息列表
    @GetMapping("/messages")
    @ApiOperation("用户消息列表")
    public Result messageList(HttpServletRequest request,@ModelAttribute() PageView pageView) {
        PageHelper.startPage(pageView.getPageIndex(), pageView.getPageSize());
        //获取请求头token
        String token = request.getHeader("token");
        if(redisUtils.haskeysf("wxMessages"+pageView)){
            PageInfo pageInfo = (PageInfo) redisUtils.getValue("wxMessages"+pageView);
            return Result.succ(200, "成功",pageInfo);
        }else {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("token", token);
            User user = userMapper.selectOne(queryWrapper);
            System.out.println("user列表");
            System.out.println(user);

            if (user != null) {
                QueryWrapper<MessageUser> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("receive_user_id", user.getId());
                List<MessageUser> messageUsers = messageUserMapper.selectList(queryWrapper1);
                System.out.println("messageUsers列表");
                System.out.println(messageUsers);
                List<Object> list = new ArrayList<>();
                if (messageUsers != null) {
                    for (MessageUser messageU : messageUsers) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", messageU.getId());
                        if (messageU.getReaded() == 1) {//1为未读，0为已读
                            map.put("readed", true);
                        } else {
                            map.put("readed", false);
                        }
                        map.put("messageId", messageU.getMessageId());

                        Message message = messageMapper.selectById(messageU.getMessageId());
                        map.put("title", message.getTitle());
                        map.put("content", message.getContent());
                        map.put("createTime", message.getCreateTime());
                        map.put("sendUserName", message.getSendUserName());
                        list.add(map);
                    }
                    PageInfo pageInfo = new PageInfo(list);
                    redisUtils.saveValue("wxMessages"+pageView,pageInfo);
                    return Result.succ(200, "查询成功", pageInfo);
                } else {
                    return Result.fail("用户没有消息");
                }
            } else {
                return Result.fail("该用户不存在");
            }
        }
    }

    //消息详情
    @GetMapping("/messageDetail/{id}")
    @ApiOperation("消息详情")
    public Result getMessageDetail(@PathVariable("id") Integer id) {
        if (redisUtils.haskeysf("wxMessageDetail" + id)) {
            Message message = (Message) redisUtils.getValue("wxMessageDetail" + id);
            return Result.succ(200, "成功",message);
        } else {
            System.out.println("消息id为多少");
            System.out.println(id);
            Message message = messageMapper.selectById(id);
            if (message != null) {
                System.out.println("在这里消息查询成功了");
                System.out.println(message);
                redisUtils.saveValue("wxMessageDetail" + id, message);
                return Result.succ("查询成功", message);
            } else {
                return Result.fail("查询失败");
            }
        }
    }
    //消息未读数

    @GetMapping("/unreadCount")
    @ApiOperation("消息未读数")
    public Result getUnreadCount(HttpServletRequest request) {
        //获取请求头token
        String token = request.getHeader("token");
        if(redisUtils.haskeysf("wxUnreadCount"+token)){
            Integer  unread = (Integer) redisUtils.getValue("wxUnreadCount"+token);
            return Result.succ(200, "成功",unread );
        }else {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("token", token);
            User user = userMapper.selectOne(queryWrapper);
            QueryWrapper<MessageUser> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("receive_user_id", user.getId());
            List<MessageUser> messageUsers = messageUserMapper.selectList(queryWrapper1);

            int unRead = 0;
            for (MessageUser messageU : messageUsers) {
                if (messageU.getReaded() == 1) {
                    unRead = unRead + 1;
                }
            }
            if (unRead >= 0) {
                redisUtils.saveValue("wxUnreadCount" + token, unRead);
                return Result.succ(200, "查询成功", unRead);
            } else {
                return Result.fail("查询有误");
            }
        }
    }

    //消息标记已读
    @PutMapping("/readMessage/{id}")
    @ApiOperation("消息标记为已读")
    public Result getReadMessage(HttpServletRequest request,@PathVariable("id") Integer id) {
        //获取请求头token
        String token = request.getHeader("token");
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("token", token);
            User user = userMapper.selectOne(queryWrapper);
            //修改messageUser表
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("message_id", id);
            updateWrapper.eq("receive_user_id", user.getId());
            updateWrapper.set("readed", 0);
            int result = messageUserMapper.update(null, updateWrapper);
            if (result > 0) {
                //修改message表
                Message message = messageMapper.selectById(id);
                UpdateWrapper updateWrapper3 = new UpdateWrapper();
                updateWrapper3.eq("id", id);
                updateWrapper.set("read_count", message.getId() + 1);
                int result2 = messageMapper.update(null, updateWrapper);
                String msg = "学生" + user.getUserName() + "读取消息" + id;
                super.wxAddLog(user, msg);
                redisUtils.delAll();
                return Result.succ(200, "成功", null);
            } else {
                return Result.fail("失败");
            }
        }
}

